const modal = require('./modal')
const util = require('./util')
const TimeRange = util.TimeRange
const config = require('./config')
const schema = modal.schema
const _ = require('lodash')

const timeRangeCount = async (schemaModel, key, timeRange) => {
  const query = schemaModel.query()
  query.equalTo('status', 1)
  query.greaterThanOrEqualTo(key, timeRange[0])
  query.lessThanOrEqualTo(key, timeRange[1])
  return await query.count()
}

/**
 * 后台统计报表
 */
Parse.Cloud.define('getReport', async (request, response) => {
  const report = {
    incomes: [],  // 预估收益
    recentSevenDayIncomes: [],  // 最近七天收益
    member: {},  // 会员统计
    tbk: {} // 淘客统计
  }
  const orderQuery = schema.order().query()  // 订单查询
  const memberSchema = schema.member() // 会员查询
  const memberQuery = memberSchema.query()
  const tbkQuery = schema.tbk().query() // 淘客查询
  const timeRange = new TimeRange() // 时间段
  const RECENTDAY = 7 // 最近七日
  const lastSevenDay = timeRange.recentDays(RECENTDAY)
  orderQuery.notEqualTo('status', -1)  // 排除不结算的订单
  orderQuery.include('group.member')  // 查询member
  orderQuery.greaterThanOrEqualTo('orderDate', timeRange.lastMonth()[0])
  try {
    const orderFind = orderQuery.find()
    // 统计会员加盟信息
    const timeArray = ['lastDay', 'thisWeek', 'lastWeek', 'thisMonth', 'lastMonth']
    for (let i = 0, len = timeArray.length; i < len; i++) {
      report.member[timeArray[i]] = await timeRangeCount(memberSchema, 'createdAt', timeRange[timeArray[i]]())
    }
    memberQuery.equalTo('status', 1)
    const memberCountAll = memberQuery.count()
    // 统计淘客账号信息
    tbkQuery.equalTo('deleted', 0)
    const tbkCountAll = tbkQuery.count()

    report.member.all = await memberCountAll
    report.tbk.all = await tbkCountAll
    // 统计收益
    const incomes = await orderFind  // 所有订单
    const allIncomes = {
      property: '全部收益'
    }
    const companyIncomes = {
      property: '公司收益'
    }
    for (let i = 0, len = timeArray.length; i < len; i++) {
      const incomesTimeRange = incomes.filter((item) => {  // 各个时间段的订单
        return item.get('orderDate') >= timeRange[timeArray[i]]()[0] && item.get('orderDate') <= timeRange[timeArray[i]]()[1]
      })
      const temp = incomesTimeRange.reduce((prev, current) => {
        const group = current.get('group')
        const forecastIncome = current.get('forecastIncome')
        if (group) {
          const member = group.get('member')
          if (member) {
            const level = member.get('level')
            const shareConfig = config.shareRate[`level${level}`]  // 会员收益
            const allShareRate = Object.keys(shareConfig).reduce((sharePrev, shareCurrent) => {
              return sharePrev + shareConfig[shareCurrent]
            }, 0)
            prev.company += (100 - allShareRate) * forecastIncome / 100
          }
        }
        prev.all += forecastIncome
        return prev
      }, {all: 0, company: 0})
      allIncomes[timeArray[i]] = parseFloat(temp.all.toFixed(4))
      companyIncomes[timeArray[i]] = parseFloat(temp.company.toFixed(4))
    }
    report.incomes = [allIncomes, companyIncomes]
    // 统计最近七天收益
    const recentSevenDayOrder = incomes.filter((item) => {
      return item.get('orderDate') >= lastSevenDay[0] && item.get('orderDate') <= lastSevenDay[1]
    })
    for (let i = 1; i <= RECENTDAY; i++) {
      const currentDayRange = timeRange.recentRange(i, 1)
      const year = currentDayRange[0].getFullYear()
      const month = currentDayRange[0].getMonth() + 1
      const day = currentDayRange[0].getDate()
      const date = `${year}-${month}-${day}`
      const currentDayOrder = recentSevenDayOrder.filter((item) => {
        return item.get('orderDate') >= currentDayRange[0] && item.get('orderDate') <= currentDayRange[1]
      })
      const temp = currentDayOrder.reduce((prev, current) => {
        const status = current.get('status')
        const group = current.get('group')
        const forecastIncome = current.get('forecastIncome')
        if (group) {
          const member = group.get('member')
          if (member) {
            const level = member.get('level')
            const shareConfig = config.shareRate[`level${level}`]
            const allShareRate = Object.keys(shareConfig).reduce((sharePrev, shareCurrent) => {
              return sharePrev + shareConfig[shareCurrent]
            }, 0)
            prev.company += (100 - allShareRate) * forecastIncome / 100
          }
        }
        prev.all += forecastIncome
        if (status === 1) {
          prev.count++
        }
        return prev
      }, { count: 0, all: 0, company: 0 })
      report.recentSevenDayIncomes.push({
        date,
        dealCount: temp.count,
        allForecastIncome: parseFloat(temp.all.toFixed(4)),
        companyForecastIncome: parseFloat(temp.company.toFixed(4))
      })
    }
    response.success(report)
  } catch (err) {
    response.error(err.message)
  }
})
/**
 * 通过会员统计报表（代理页面）
 */
Parse.Cloud.define('getReportByMember', async (request, response) => {
  const { id } = request.params
  if (!id) {
    return response.error('请提供需要统计的会员Id')
  }
  try {
    const timeRange = new TimeRange() // 时间段
    // 用户查询
    const member = schema.member()
    const memberQuery = member.query()
    const subMemberQuery = member.query()
    memberQuery.equalTo('objectId', id)
    memberQuery.equalTo('status', 1)
    const currentMember = await memberQuery.first()
    if (!currentMember) {
      return response.error('用户不存在')
    }
    // 下级用户查询
    member.id = id
    const subMembers = await util.getSubMembers(member, config.deep)
    subMemberQuery.equalTo('status', 1)
    subMemberQuery.containedIn('objectId', subMembers.map(item => item.id))
    const subMemberFind = subMemberQuery.find()
    // 账户查询
    const accountQuery = schema.account().query()
    accountQuery.equalTo('member', member)
    const accountFind = accountQuery.first()
    // 查询对应用户的收入统计表
    const now = new Date()
    let incomes = schema.incomes()
    const incomesQuery = incomes.query()
    incomesQuery.equalTo('member', member)
    incomesQuery.greaterThanOrEqualTo('updatedAt', new Date(now.getFullYear(), now.getMonth(), now.getDate()))
    const existIncome = await incomesQuery.first()
    const timeArray = ['lastDay', 'thisWeek', 'lastWeek', 'thisMonth', 'lastMonth']
    const selfForecastIncome = {}  // 自己群的收入
    const subForecastIncome = {} // 下级带来的收入
    // 如果收入统计已经更新过，直接查询收入表中的数据
    if (existIncome) {
      for (let i = 0, len = timeArray.length; i < len; i++) {
        selfForecastIncome[timeArray[i]] = existIncome.get(`self${_.upperFirst(timeArray[i])}`)
        subForecastIncome[timeArray[i]] = existIncome.get(`sub${_.upperFirst(timeArray[i])}`)
      }
    } else {  // 否则，通过订单查询
      const newIncomeQuery = incomes.query()
      newIncomeQuery.equalTo('member', member)
      incomes = await newIncomeQuery.first() || incomes
      incomes.set('member', member)

      const orderQuery = schema.order().query()
      const groupQuery = schema.group().query()
      const subOrderQuery = schema.order().query()
      const subGroupQuery = schema.group().query()
      // 本人群的订单
      orderQuery.notEqualTo('status', -1)  // 排除不结算的订单
      orderQuery.greaterThanOrEqualTo('orderDate', timeRange.lastMonth()[0])
      groupQuery.equalTo('status', 1)
      groupQuery.equalTo('member', member)
      orderQuery.matchesQuery('group', groupQuery)
      // 下级群订单
      subOrderQuery.notEqualTo('status', -1)
      subOrderQuery.greaterThanOrEqualTo('orderDate', timeRange.lastMonth()[0])
      subOrderQuery.include('group.member')
      subGroupQuery.equalTo('status', 1)
      subGroupQuery.containedIn('member', subMembers.map((item) => {
        const subMember = schema.member()
        subMember.id = item.id
        return subMember
      }))
      subOrderQuery.matchesQuery('group', subGroupQuery)

      const orderFind = orderQuery.find()
      const subMemberOrderFind = subOrderQuery.find()
      const orders = await orderFind
      const subOrders = await subMemberOrderFind
      // 统计本人的订单
      for (let i = 0, len = timeArray.length; i < len; i++) {
        const orderTimeRange = orders.filter((item) => {  // 各个时间段的订单
          return item.get('orderDate') >= timeRange[timeArray[i]]()[0] && item.get('orderDate') <= timeRange[timeArray[i]]()[1]
        })
        const total = orderTimeRange.reduce((prev, current) => {
          const forecastIncome = current.get('forecastIncome')
          const level = currentMember.get('level')
          const shareConfig = config.shareRate[`level${level}`]  // 会员收益
          return prev + forecastIncome * shareConfig.self / 100
        }, 0)
        const formatTotal = parseFloat(total.toFixed(4))
        selfForecastIncome[timeArray[i]] = formatTotal
        incomes.set(`self${_.upperFirst(timeArray[i])}`, formatTotal)
      }
      // 统计下级订单
      for (let i = 0, len = timeArray.length; i < len; i++) {
        const orderTimeRange = subOrders.filter((item) => {  // 各个时间段的订单
          return item.get('orderDate') >= timeRange[timeArray[i]]()[0] && item.get('orderDate') <= timeRange[timeArray[i]]()[1]
        })
        const total = orderTimeRange.reduce((prev, current) => {
          const forecastIncome = current.get('forecastIncome')
          let rate = 0
          const group = current.get('group')
          if (group) {
            const subMember = group.get('member')
            const level = subMember.get('level')
            const shareRateConfig = config.shareRate[`level${level}`]  // 会员收益
            const memberLevel = subMembers.find((item) => item.id === subMember.id)
            rate = shareRateConfig[`parent${memberLevel.deep}`]
          }
          return prev + forecastIncome * rate / 100
        }, 0)
        const formatTotal = parseFloat(total.toFixed(4))
        incomes.set(`sub${_.upperFirst(timeArray[i])}`, formatTotal)
        subForecastIncome[timeArray[i]] = formatTotal
      }
      await incomes.save()  // 将查询出来的数据保存到收入表中
    }
    // 查询下级
    const mySubmember = await subMemberFind
    const account = await accountFind
    const subMemberArray = mySubmember.map((item) => {
      const level = item.get('level')
      const shareRateConfig = config.shareRate[`level${level}`]  // 会员收益
      const memberLevel = subMembers.find((item) => item.id === item.id)
      const rate = shareRateConfig[`parent${memberLevel.deep}`]
      return {
        id: item.id,
        name: item.get('name'),
        level,
        shareRate: rate
      }
    })
    const selfIncomes = account.get('selfIncomes') || 0
    const subIncomes = account.get('subIncomes') || 0
    const cashing = account.get('cashing') || 0
    const cashed = account.get('cashed') || 0
    response.success({
      account: {
        remaining: parseFloat((selfIncomes + subIncomes - cashing - cashed).toFixed(4)),
        cashing
      },
      subMember: subMemberArray,
      selfForecastIncome,
      subForecastIncome
    })
  } catch (err) {
    response.error(err.message)
  }
})